//
// Created by ChenJi on 2021/4/13.
//

#include "door_manager.h"

Door_Sensor sensor_1 = {1, 0, 1, 0, 100};
Door_Sensor sensor_2 = {1, 0, 1, 0, 100};

uint8_t now_door_state = 0;

void kernel_door_slow_tick_1ms() {
    sensor_1.stable_time++;
    sensor_2.stable_time++;
    if (sensor_1.chenged) {
        if (sensor_1.filtering_threshold <= sensor_1.stable_time) {
            onDoorSensor_1_Chenged(sensor_1.now_state);
            sensor_1.chenged = 0;
            updateDoorState();
        }
    }
    if (sensor_2.chenged) {
        if (sensor_2.filtering_threshold <= sensor_2.stable_time) {
            onDoorSensor_2_Chenged(sensor_2.now_state);
            sensor_2.chenged = 0;
            updateDoorState();
        }
    }
}

void onGPIOSwap_12(GPIO_PinState sta) {
    if (sta) {
        sensor_1.chenged = 1;
        sensor_1.now_state = 1;
        LED_G_SET;
    } else {
        sensor_1.chenged = 1;
        sensor_1.now_state = 0;
        LED_G_RESET;
    }
}

void onGPIOSwap_13(GPIO_PinState sta) {
    if (sta) {
        sensor_2.chenged = 1;
        sensor_2.now_state = 1;
        LED_B_SET;
    } else {
        sensor_2.chenged = 1;
        sensor_2.now_state = 0;
        LED_B_RESET;
    }
}

void updateDoorState() {
    uint8_t now_State = (sensor_1.chenged == 0 && sensor_1.now_state == 1 && sensor_2.chenged == 0 &&
                         sensor_2.now_state == 1);
    if (now_State != now_door_state) {
        if (now_State) onDoorOpen();
        else onDoorClose();
        now_door_state = now_State;
    }
}

void DoorManagerInit() {
    if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_12) && HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_13))onDoorOpen();
    else
        onDoorClose();
}

